﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Configuration;
using System.IO;
using LeadVinaglue.Models.ViewPages;
using LeadVinaglue.Models;
using LeadVinaglue.Repository;
using LeadVinaglue.Utility;
using LeadVinaglue.Helpers;

namespace LeadVinaglue.Areas.Management.Controllers
{
    public class ProductListController : Controller
    {
        // Create an instance of user manage
        LeadVinaglue.Repository.ProductManagementRepository repository = new LeadVinaglue.Repository.ProductManagementRepository();
        public static string ProductImagesURL = ConfigurationManager.AppSettings["ProductImagesURL"].ToString();
        public static string ProductSmallImagesURL = ConfigurationManager.AppSettings["ProductSmallImagesURL"].ToString();
        public static string ProductMediumImagesURL = ConfigurationManager.AppSettings["ProductMediumImagesURL"].ToString();
        public static string ProductShareImagesURL = ConfigurationManager.AppSettings["ProductShareImagesURL"].ToString();

        // GET: /Management/Home/
        [Authorize(Roles = "SuperAdministrator")]
        public ActionResult Index()
        {
            ProductManagementModel model = new ProductManagementModel();
            model = repository.GetModel(Helpers.Constant.HOME, "SuperAdministrator", 10, 1);

            return View(model);
        }

        // GET: /Management/Home/
        [Authorize(Roles = "SuperAdministrator")]
        public ActionResult Preview(int id)
        {
            ProductPreviewModel model = new ProductPreviewModel();
            model = repository.GetModelPreview (id);

            return View(model);
        }

        // GET: /Management/Home/
        [Authorize(Roles = "SuperAdministrator")]
        public ActionResult UpdatePreview(int id, string action)
        {
            // Update Product
            var prod = repository.GetSingle(id);

            if (prod != null)
            {
                prod.Active = true;
                repository.Update(prod);
            }


            string model = string.Empty;
            model = "ok";

            return Json(model);
        }

        // GET: /Management/Product/Search?keywords=tt&fieldName=type
        [Authorize(Roles = "SuperAdministrator")]
        public ActionResult Search(string keywords, string fieldName)
        {
            ProductManagementModel model = new ProductManagementModel();
            model = repository.GetModel(Helpers.Constant.HOME, "SuperAdministrator", keywords, fieldName, 10, 1);
            model.Keywords = keywords;
            model.FieldName = fieldName;

            return View(model);
        }


        [HttpPost]
        public ActionResult Fillter(string keywords, string startDate, string endDate, string categoryId, int pageSize, int pageIndex, int id, string sortBy, string sortOrder)
        {
            ProductManagementModel model = new ProductManagementModel();
            string[] categories = categoryId.Split(',');

            model = repository.GetModel(Helpers.Constant.HOME, "SuperAdministrator", keywords, startDate, endDate, categories, sortBy, sortOrder, pageSize, pageIndex, id);

            return Json(model);
        }


        [HttpPost]
        public ActionResult SearchFillter(string keywords, string fieldName, int pageSize, int pageIndex)
        {
            ProductManagementModel model = new ProductManagementModel();
            model = repository.GetModelSearch(keywords, fieldName, pageSize, pageIndex);
            model.Keywords = keywords;
            model.FieldName = fieldName;

            return Json(model);
        }

        [Authorize(Roles = "SuperAdministrator")]
        public ActionResult Edit(int id)
        {
            ProductManagementModel model = new ProductManagementModel();
            model = repository.GetModel(Helpers.Constant.HOME, "SuperAdministrator", id);

            ViewBag.ProductId = id;

            return View(model);
        }

        [HttpPost]
        [ValidateInput(false)]
        [Authorize(Roles = "SuperAdministrator")]
        public ActionResult Edit(int id, FormCollection form)
        {
            Product model = repository.GetSingle(id);

            if (model != null)
            {
                model.Title = form["Title"].ToString();
                model.LongDesc = form["LongDesc"].ToString();
                model.ImageURL = form["ImageUrl"].ToString();
                model.CategoryID = (form["CategoryID"] != null) ? int.Parse(form["CategoryID"].ToString()) : 0;
                model.SubCategoryID = (form["SubCategoryID"] != null) ? int.Parse(form["SubCategoryID"].ToString()) : 0;
                model.Active = (form["Active"] != null && form["Active"].ToString() == "on");

                // Transaction
                repository.Update(model);
            }

            return RedirectToAction("Index", "ProductList");
        }

        [HttpPost]
        public ActionResult Upload(HttpPostedFileBase fileData)
        {
            // Verify that the user selected a file
            string fileName = string.Empty;
            UploadModel model = new UploadModel();

            if (fileData != null && fileData.ContentLength > 0)
            {
                // extract only the fielname
                fileName = Path.GetFileName(fileData.FileName);
                string originalFileName = Path.GetFileName(fileData.FileName);
                string prefix = new Random().Next(1000000, 9999999).ToString();
                string guid = Guid.NewGuid().ToString();

                // clear special chars
                fileName = string.Format("{0}{1}", StringClearFormat.ClearSpecials(fileName.Substring(0, fileName.Length - 4)), fileName.Substring(fileName.Length - 4, 4));

                originalFileName = string.Format("{0}-{1}", prefix, fileName);
                fileName = string.Format("{0}-{1}", guid, fileName);

                // store the file inside ~/App_Data/uploads folder
                var path = Path.Combine(Server.MapPath(ProductImagesURL), originalFileName);
                fileData.SaveAs(path);

                model.FileName = originalFileName;
                model.ImageUrl = string.Format("{0}/{1}", ProductImagesURL, originalFileName);

                // Make thumbnail small/medium images
                // First: Save images.
                fileData.SaveAs(Path.Combine(Server.MapPath(ProductSmallImagesURL), fileName));
                fileData.SaveAs(Path.Combine(Server.MapPath(ProductMediumImagesURL), fileName));
                fileData.SaveAs(Path.Combine(Server.MapPath(ProductShareImagesURL), fileName));

                // Second: Resize image.
                FileHelper.SaveResizedImage(Server.MapPath(ProductSmallImagesURL), fileName, originalFileName, 45, 45);
                FileHelper.SaveResizedImage(Server.MapPath(ProductMediumImagesURL), fileName, originalFileName, 75, 75);
                FileHelper.SaveResizedImage(Server.MapPath(ProductShareImagesURL), fileName, originalFileName, 100, 100);

            }
            // redirect back to the index action to show the form once again
            return Json(model);
        }
    }
}
